package com.panda;

import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import com.alibaba.fastjson.JSONObject;

public class SocketServer extends WebSocketServer {

	private Map<String, WebSocket> users = new HashMap<String, WebSocket>();
	private List<String> userList = new ArrayList<String>();
	private int count = 0;
	
	public SocketServer() throws UnknownHostException {
		
    }
	
    public SocketServer(int port) throws UnknownHostException {
        super(new InetSocketAddress(port));
        System.out.println("websocket Server start at port:"+port);
    }
	
    /**
     * 	触发连接事件
     */
	@Override
	public void onOpen(WebSocket conn, ClientHandshake handshake) {
		System.out.println("onOpen");
		users.put(++count + "", conn);
		userList.add(count + "");
		JSONObject json = new JSONObject();
		json.put("id", count);
		json.put("type", "userInfo");
		json.put("userList", userList);
		conn.send(json.toJSONString());
	}

	/**
	 * 	连接断开时触发关闭事件
	 */
	@Override
	public void onClose(WebSocket conn, int code, String reason, boolean remote) {
		System.out.println("onClose");
	}

	/**
	 *	 客户端发送消息到服务器时触发事件
	 */
	@Override
	public void onMessage(WebSocket conn, String message) {
		System.out.println("onMessage");
		System.out.println("message: "+ message);
		JSONObject json = JSONObject.parseObject(message);
		String to = json.getString("to");//接受者
		String content = json.getString("content");//发送内容
		
		JSONObject result = new JSONObject();
		result.put("content", content);
		result.put("type", "message");
		
        //向客户端发送消息
    	conn.send(result.toJSONString());
    	WebSocket toSocket = users.get(to);
    	toSocket.send(result.toJSONString());
	}

	/**
	 * 	触发异常事件
	 */
	@Override
	public void onError(WebSocket conn, Exception ex) {
		System.out.println("onError");
		ex.printStackTrace();
		if( conn != null ) {
            //some errors like port binding failed may not be assignable to a specific websocket
        }
	}

	/**
	 * 	启动服务端
	 */
	@Override
	public void onStart() {
		System.out.println("onStart");
	}
	
	
	public static void main(String[] args) {
		try {
			new SocketServer(453).start();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}

}
